<template>
  <el-dialog
    v-model="dialogFormVisible"
    class="dialog-wrap"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <template #header>
      <div class="dialog-title">
        {{ title }}
      </div>
    </template>

    <el-form
      ref="ruleForm"
      class="ruleForm ruleForm-g2"
      :disabled="formDisabled"
      label-width="auto"
      :model="form"
      :rules="rules"
      style="max-width: 600px"
    >
      <el-form-item label="所属学院" prop="collegeId">
        <el-select
          v-model="form.collegeId"
          clearable
          placeholder="请选择所属学院"
          @change="form.professionId = null"
        >
          <el-option
            v-for="item in collegeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属系" prop="professionId">
        <el-select
          v-model="form.professionId"
          clearable
          placeholder="请选择所属系"
        >
          <el-option
            v-for="item in professionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级年份" prop="grade">
        <el-date-picker
          v-model="form.grade"
          placeholder="请选择班级年份"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>

      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model.trim="form.className"
          maxlength="20"
          placeholder="请输入班级名称"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="培养层次" prop="dictCultivationLevel">
        <el-select
          v-model="form.dictCultivationLevel"
          clearable
          placeholder="请选择培养层次"
        >
          <el-option
            v-for="dict in cultivation_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级代码" prop="classCode">
        <el-input
          v-model.trim="form.classCode"
          maxlength="20"
          placeholder="请输入班级代码"
          show-word-limit
        />
      </el-form-item>

      <el-form-item class="column-all" label="备注信息" prop="note">
        <el-input
          v-model.trim="form.note"
          maxlength="300"
          placeholder="填写班级备注信息（非必填）"
          rows="6"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        >
        <el-button @click="dialogFormVisible = false">取 消</el-button>

        <el-button type="primary" @click="submitForm(ruleForm)">
          > 确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import $api from './api.js'
  import { extend } from '@/utils/tool.js'

  const emits = defineEmits(['save'])
  const { proxy } = getCurrentInstance()

  // 获取静态字典
  const { cultivation_level } = proxy.useDict('cultivation_level')

  // data
  const dialogFormVisible = ref(false)
  const loadType = ref('add')
  const title = ref('')
  const formDisabled = ref(false)
  const ruleForm = ref()
  const def = {
    id: null,

    // 院系id
    collegeId: '',

    // 专业id
    professionId: '',

    // 入学年份
    grade: '',

    // 班级名称
    className: '',

    // 班级代码
    classCode: '',

    // 备注
    note: '',

    // 字典 培养层次 cultivation_level
    dictCultivationLevel: '',
  }
  let form = ref(extend(def))

  const rules = reactive({
    collegeId: [
      { required: true, message: '所属学院不能为空', trigger: 'blur' },
    ],
    professionId: [
      { required: true, message: '所属系不能为空', trigger: 'blur' },
    ],
    grade: [{ required: true, message: '班级年份不能为空', trigger: 'blur' }],
    className: [
      { required: true, message: '班级名称不能为空', trigger: 'blur' },
    ],
    dictCultivationLevel: [
      { required: true, message: '培养层次不能为空', trigger: 'blur' },
    ],

    classCode: [
      { min: 0, max: 20, message: '长度应为0~20个字符', trigger: 'blur' },
      {
        message: '只能填写字母、数字和“-”',
        trigger: 'blur',
        validator: (rule, value, callback) => {
          // 修改了正则表达式，添加了对 "-" 的匹配
          // 注意在 '-' 前面没有添加 '\', 因为在字符集合[]内，'-' 本身不作为特殊字符处理
          const reg = /^[a-zA-Z0-9\-]+$/
          if (!value) {
            callback()
            return
          }
          if (reg.test(value)) {
            callback()
          } else {
            callback(new Error(rule.message))
          }
        },
      },
    ],
    note: [
      { min: 0, max: 300, message: '长度应为0~300个字符', trigger: 'blur' },
    ],
  })

  // 方法
  async function load(type, d) {
    dialogFormVisible.value = true
    await nextTick()
    reset()

    const titleStr = '班级信息'
    loadType.value = type

    if (loadType.value === 'detail') {
      formDisabled.value = true
      title.value = `查看${titleStr}`
      for (let f1 in d) {
        form.value[f1] = d[f1]
      }
    }

    if (loadType.value === 'add') {
      title.value = `添加${titleStr}`
    }

    if (loadType.value === 'edit') {
      title.value = `修改${titleStr}`
      for (let f1 in d) {
        form.value[f1] = d[f1]
      }
    }
  }

  function reset() {
    formDisabled.value = false
    ruleForm.value.resetFields()
    const d = extend(def)
    for (let f1 in d) {
      form.value[f1] = d[f1]
    }
  }

  const submitForm = async (formEl) => {
    if (!formEl) {
      return
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        // console.log('submit!')
        if (loadType.value === 'add') {
          add()
        }

        if (loadType.value === 'edit') {
          edit()
        }
      }
    })
  }

  const add = function () {
    const sendData = {
      ...form.value,
    }

    $api.add(sendData).then((res) => {
      proxy.$modal.msgSuccess('新增成功')
      emits('save')
      dialogFormVisible.value = false
    })
  }

  const edit = function () {
    const sendData = {
      ...form.value,
    }

    $api.edit(sendData).then((res) => {
      proxy.$modal.msgSuccess('修改成功')
      emits('save')
      dialogFormVisible.value = false
    })
  }

  defineExpose({
    load,
  })
</script>

<style lang="scss" scoped></style>
